<template>
  <div class="file-manage-container">
    
    <!-- 这部分内容已移至按钮下方 -->
    <div class="file-bread">
      <div class="bread-box">
        <div class="header-l">
          <el-breadcrumb class="breadcrumb-container">
            <el-breadcrumb-item>文件存储</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-nav-right">
          <div class="flexs-layout btn-box r" v-if="folderShow && permUpload">
            <div class="item-upload">
              <div v-if="!navBtnShow">
                <el-button size="default"
                           type="primary"
                           style="width:100px;"
                           class="btnPadding815"
                           disabled>
                  <el-icon style="margin-right: 5px;"><Upload /></el-icon>
                  上传
                </el-button>
              </div>
              <FileUpload v-else
                        ref="uploadChild"
                        :folderCreatedCast="folderCreatedCast"
                        @uploadPath="uploadPathFn"
                        @folderCreatedEmit="folderCreatedEmit"></FileUpload>
            </div>
            <div class="item" style="margin-left: 10px;">
              <el-button size="default"
                        @click="newRightClickDialog"
                        class="btnPadding815"
                        :disabled="!navBtnShow">
                <el-icon style="margin-right: 5px;"><FolderAdd /></el-icon>
                新建文件夹
              </el-button>
              <span v-if="selectedList.length > 0 && !inverse" style="margin-left: 10px;">
                <el-button size="default" class="btnPadding815" @click="deleteAll" :disabled="!navBtnShow">
                  <el-icon style="margin-right: 5px;"><Delete /></el-icon>删除
                </el-button>
                <el-button size="default" class="btnPadding815" @click="copyAllSelect" :disabled="!navBtnShow">
                  <el-icon style="margin-right: 5px;"><CopyDocument /></el-icon>复制
                </el-button>
                <el-button size="default" class="btnPadding815" @click="moveAllSelect" :disabled="!navBtnShow">
                  <el-icon style="margin-right: 5px;"><ArrowRight /></el-icon>移动
                </el-button>
                <el-button size="default" class="btnPadding815" :disabled="selectedList.length > 1" @click="renameBtn">
                  <el-icon style="margin-right: 5px;"><Edit /></el-icon>重命名
                </el-button>
                <el-button size="default" class="btnPadding815" :disabled="selectedList.length < 1" @click="() => downRightClick()">
                  <el-icon style="margin-right: 5px;"><Download /></el-icon>下载
                </el-button>
              </span>
            </div>
          </div>
          <div class="btn-box r" v-if="recShow">
            <el-button size="default" type="primary" class="btn-select-btn btnPadding815" @click="recoveryAllSelect">
              <el-icon><Refresh /></el-icon>恢复
            </el-button>
            <el-button size="default" class="btn-select-btn btnPadding815" @click="completeDeleAll">
              <el-icon><Delete /></el-icon>彻底删除
            </el-button>
          </div>
          <div>
          <div class="search-boxs" style="display: flex; align-items: center;">
              <div class="item" style="width:100px;">
                <el-select v-model="search.key" :disabled="!navBtnShow" @change="searchChange" size="default">
                  <el-option label="文件名" value="0" />
                  <el-option label="fid" value="1" />
                </el-select>
              </div>
              <div class="item straight">
                <el-input placeholder="请输入..." :disabled="!navBtnShow" v-model.trim="search.word" @keyup.enter="searchBtn" size="default" />
              </div>
              <el-button @click="searchBtn" :disabled="!navBtnShow" type="primary" size="default" class="btnPadding815 btn-select-bg" style="border-top-left-radius: 0;border-bottom-left-radius: 0;">搜索</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="file-container main-common">
      <div class="main">
        <div class="main-items left-parts" v-loading="leftTreeLoading" element-loading-text="正在加载中">
          <div class="tests-nav"></div>
          <!-- 左侧树 -->
          <div class="left-tree">
            <div class="folder-box">
              <FileTree dialogOrLeft="left"
                        :treeDemo="leftNewTreeId"
                        onlyFolder="folder"
                        ref="selectFileNewTree"
                        :localPath="true"
                        :backupStatus="backupStatus"
                        @publicPath="publicPathFnLeftTree"
                        @backflag="backflagFn"
                        @backupStatus="backupStatusFn"
                        @leftTreeLoading="leftTreeLoadingFn"
                        @clickInfo="clickInfoFn"
                        @treeClickNum="treeClickNumFn"
                        @updateFileList="updateFileList"
                        @routerPathOk="routerPathOk" />
            </div>
            
            <!-- 挂载设备 -->
            <div class="fixed-directory" @click="showDeviceList">
              <div class="dir-item" :class="{ 'active': currentViewType === 'device' }">
                <img v-if="currentViewType === 'device'" src="../assets/folderopen.png" alt="打开的文件夹" width="16px" height="15px" class="folder-icon" />
                <img v-else src="../assets/folder.png" alt="文件夹" width="16px" height="15px" class="folder-icon" />
                <span class="dir-label">挂载设备</span>
              </div>
            </div>
            
            <!-- 回收站 -->
            <div class="fixed-directory">
              <div class="dir-item" @click="showRecycleBin" :class="{ 'active': currentViewType === 'recycle' }">
                <img v-if="currentViewType === 'recycle'" src="../assets/folderopen.png" alt="打开的文件夹" width="16px" height="15px" class="folder-icon" />
                <img v-else src="../assets/folder.png" alt="文件夹" width="16px" height="15px" class="folder-icon" />
                <span class="dir-label">回收站</span>
              </div>
            </div>
          </div>
          <!--剩余空间 -->
          <div class="user-space-info">
            <div class="progress-box">
              <el-progress :percentage="spacePercent" :show-text="false" />
            </div>
            <span>{{ spaceCurrent }}/{{ spaceTotal }}</span>
          </div>
        </div>
        <div class="main-items right-parts">
          <!-- 文件夹操作右侧树 -->
          <div v-if="currentViewType === 'folder'" class="folder-right-operate">
            <!-- 返回上一级 -->
            <div class="bread-box">
              <div class="l" style="display:flex; align-items:center; margin:0; padding:0;">
                <span v-if="backflag" @click="backUpClick">返回上一级 |</span>
                <span :class="!backflag ? 'color333' : ''" @click="mySpaceClick">我的空间</span>
                <span v-if="backflag">></span>
                <template v-if="crumbList.length > 0">
                  <span v-for="(item, index) in crumbList" :key="index" @click="addBtnFlag && breadClick(item)" class="nav-item">
                    {{ item }}
                    <span v-if="index < crumbList.length - 1 && item !== ''">></span>
                  </span>
                </template>
              </div>
            </div>
            <div class="file-title">
              <input type="checkbox" v-model="checkedAll" @change="checkAll" :disabled="!navBtnShow || searchShow" class="title-input" />
              <span class="item name sort-box">
                文件名
                <span class="caret-wrapper">
                  <i @click="sortSelf('name', 'nameup')" class="sort-caret ascending" :class="{ 'blue-bottom': sorttypeName === 'nameup' }" />
                  <i @click="sortSelf('name', 'namedown')" class="sort-caret descending" :class="{ 'blue-top': sorttypeName === 'namedown' }" />
                </span>
              </span>
              <span class="item sort-box">
                文件大小
                <span class="caret-wrapper">
                  <i @click="sortSelf('fsize', 'fsizeup')" class="sort-caret ascending" :class="{ 'blue-bottom': sorttypeName === 'fsizeup' }" />
                  <i @click="sortSelf('fsize', 'fsizedown')" class="sort-caret descending" :class="{ 'blue-top': sorttypeName === 'fsizedown' }" />
                </span>
              </span>
              <span class="item sort-box">
                创建时间
                <span class="caret-wrapper">
                  <i @click="sortSelf('ctime', 'ctimeup')" class="sort-caret ascending" :class="{ 'blue-bottom': sorttypeName === 'ctimeup' }" />
                  <i @click="sortSelf('ctime', 'ctimedown')" class="sort-caret descending" :class="{ 'blue-top': sorttypeName === 'ctimedown' }" />
                </span>
              </span>
              <span class="item sort-box" v-if="searchShow">所在目录</span>
            </div>
            <div v-loading="rightOperateLoading" element-loading-text="正在加载中">
              <div class="right-list-container" v-if="rightList.length > 0">
                <p v-for="(item, index) in rightList" :key="index" class="right-list-item" :class="{ 'table-select-bg': item.checked }" @mousedown="removePrevItem(index)">
                  <input type="checkbox" v-model="item.checked" @change="singleSelect(item)" class="input-select-item" :disabled="!navBtnShow || searchShow" />
                  <span @click="!item.unbind && childNodeClick(item)" @contextmenu.prevent="showMenu(item, index, item.filetype)" class="item-inner" @dblclick="dbclickOpen(item)">
                    <img v-if="item.filetype === '0' || item.filetype === '6'" src="../assets/folder.png" alt="文件夹" width="16px" height="15px" class="imgs" />
                    <img v-else-if="item.filetype === '2'" src="../assets/icon-img.png" alt="图片" width="16px" height="17px" class="imgs" />
                    <img v-else-if="item.filetype === '4'" src="../assets/icon-audio.png" alt="音频" width="16px" height="17px" class="imgs" />
                    <img v-else-if="item.filetype === '7'" src="../assets/video.png" alt="视频" width="16px" height="17px" class="imgs" />
                    <img v-else-if="item.filetype === '3' || item.filetype === '1' || item.filetype === '5'" src="../assets/icon-document.png" alt="文档" width="16px" height="17px" class="imgs" />
                    <img v-else src="../assets/icon-unknown.png" alt="未知" width="16px" height="17px" class="imgs" />
                    <input v-if="item.currentShowFlag === '1'" v-model="item.name" id="inputMark" @change="modifyNameClick" @blur.prevent="blurEvent(item)" @keyup.enter="blurEvent(item)" />
                    <span v-else :title="item.name">{{ item.name }}</span>
                  </span>
                  <span class="right-list-options">
                    <span v-if="item.filetype !== '0' && item.filetype !== '6' && item.fsize">{{ formatFileSize(item.fsize) }}</span>
                    <span v-else>-</span>
                  </span>
                  <span class="right-list-options">{{ item.ctime }}</span>

                </p>
              </div>
              <div v-else class="right-list-container">
                <p style="padding:20px;">暂无文件</p>
              </div>
            </div>
            
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next"
                :total="total"
                :page-size="pageSize"
                :current-page="currentPage"
                :page-sizes="[10, 30, 50, 100, 200]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="margin-bottom: 20px;"
                v-if="!searchShow">
              </el-pagination>
              <el-pagination
                background
                layout="total, sizes, prev, pager, next"
                :total="searchPage.total"
                :page-size="searchPage.numPerPages"
                :current-page="searchPage.currentPage"
                :page-sizes="[10, 30, 50, 100, 200]"
                @size-change="searchHandleSizeChange"
                @current-change="searchHandleCurrentChange"
                style="margin-bottom: 20px;"
                v-else>
              </el-pagination>
            </div>
          </div>
          
          <!-- 设备列表展示 -->
          <div v-else-if="currentViewType === 'device'" class="folder-right-operate">
            <div class="bread-box">
              <div class="l">
                <span class="color333">挂载设备</span>
              </div>
            </div>
            <div class="file-title">
              <span class="item name">设备名称</span>
              <span class="item">IP地址</span>
              <span class="item">挂载路径</span>
              <span class="item">连接状态</span>
            </div>
            <div v-loading="rightOperateLoading" element-loading-text="正在加载中">
              <div class="right-list-container" v-if="deviceList.length > 0">
                <p v-for="(device, index) in deviceList" :key="index" class="right-list-item">
                  <span class="item-inner">
                    <img src="../assets/folder.png" alt="设备" width="16px" height="15px" class="imgs" />
                    <span :title="device.name">{{ device.name }}</span>
                  </span>
                  <span class="right-list-options">{{ device.ip }}</span>
                  <span class="right-list-options">{{ device.path }}</span>
                  <span class="right-list-options" :class="device.status === '在线' ? 'status-online' : 'status-offline'">
                    {{ device.status }}
                  </span>
                </p>
              </div>
              <div v-else class="right-list-container">
                <p style="padding:20px;">暂无挂载设备</p>
              </div>
            </div>
          </div>
          
          <!-- 回收站 -->
          <div v-else-if="currentViewType === 'recycle'" class="folder-right-operate recycled-box">
            <div class="rec-header">回收站列表</div>
            <div class="file-title recycled">
              <input type="checkbox" v-model="checkedRecAll" @change="checkRecAll" class="title-input" />
              <span class="item name">文件名</span>
              <span class="item">文件大小</span>
              <span class="item">删除时间</span>
            </div>
            <div class="right-parts right-list-container">
              <p v-for="(item, index) in recycleList" :key="index" class="right-list-item">
                <input type="checkbox" v-model="item.checked" class="input-select-item" />
                <span class="item-inner">
                  <img src="../assets/icon-document.png" alt="文件" width="16px" height="17px" class="imgs" />
                  <span :title="item.name">{{ item.name }}</span>
                </span>
                <span class="right-list-options">{{ item.size }}</span>
                <span class="right-list-options">{{ item.deleteTime }}</span>
              </p>
              <div v-if="recycleList.length === 0" style="padding:20px;">回收站为空</div>
            </div>
          </div>
        </div>
      </div>
    </div>
        <!-- 创建文件夹组件 -->
        <CreateFolder
          v-model:visible="createFolderVisible"
          :current-path="paths"
          @create-success="handleFolderCreatedEmit()"
        />
        
        <!-- 复制和移动文件选择器组件 -->
        <FileTree 
          v-if="switchFlagCopyAll" 
          :dialogOrLeft="'dialog'" 
          :treeDemo="'treeDemoCopyAll'" 
          ref="selectFileCopyAll"
          @routerPathOk="copyAll">
        </FileTree>
        <FileTree 
          v-if="switchFlagMoveAll" 
          :dialogOrLeft="'dialog'" 
          :treeDemo="'treeDemoMoveAll'" 
          ref="selectFileMoveAll"
          @routerPathOk="moveAll">
        </FileTree>
        
        <!-- 右键菜单组件 -->
        <ContextMenu
          :visible="contextMenuVisible"
          :x="contextMenuX"
          :y="contextMenuY"
          :menu-items="menuItems"
          @click="handleContextMenuClick"
          @close="contextMenuVisible = false"
        />
        

        <!-- 视频预览对话框 -->
        <VideoPlayer
          :dialog-preview-video="dialogPreviewVideo"
          :video-url="videoUrl"
          :file-format="fileFormat"
          :play-list="playList"
          :fid="fid"
          @close="handleCloseVideo"
          @flash-click="flashClick"
          @handle-open="handleOpen"
          @curent-video="curentVideo"
        />
        
        <!-- 图片预览对话框 -->
        <PictureDialog
          :dialog-preview-img="dialogPreviewImg"
          :dialog-imgurl="dialogImgurl"
          :pic-info="picInfo"
          @handle-close-img="handleCloseImg"
        />
        
        <!-- 文件元数据对话框 -->
        <FileMeta
          :file-meta-dialog-flag="fileMetaDialogFlag"
          :file-meta-obj="fileMetaObj"
          @handle-close-img="handleCloseImg"
        />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed, onUnmounted } from 'vue'
import { ElMessage, ElPagination, ElMessageBox, ElNotification } from 'element-plus'
import { Upload, FolderAdd, Delete, CopyDocument, ArrowRight, Edit, Download, Refresh } from '@element-plus/icons-vue'
import FileUpload from './FileUpload.vue'
import FileTree from './FileTree.vue'

import CreateFolder from './CreateFolder.vue'
import ContextMenu from './ContextMenu.vue'
import VideoPlayer from './VideoPlayer.vue'
import PictureDialog from './PictureDialog.vue'
import FileMeta from './FileMeta.vue'
import { FileType } from '../utils/mockData'
import { formatFileSize, calculateSpacePercent } from '../utils/fileUtils.js'
import { asyncGetFolderList, asyncfileMeta,asyncGetData, getSpaceInfo, getRecycleBinList, getDeviceList, asyncRenameFolder, asyncRenameFile } from '../api/fileManage'

// 响应式数据
const folderShow = ref(true)
const permUpload = ref(true)
const navBtnShow = ref(true)
const folderCreatedCast = ref(false)
const leftTreeLoading = ref(false)
const rightOperateLoading = ref(false)
const backflag = ref(false)
const crumbList = ref([])
const paths = ref('')
const search = reactive({
  key: '0',
  word: ''
})
const searchShow = ref(false)
const checkedAll = ref(false)
const allDataList = ref([]) // 完整数据列表
const rightList = ref([]) // 当前页显示的数据列表
const selectedList = ref([])
const sorttypeName = ref('')
const sortTypeNumber = ref('')
const orderStyle = ref('')
const spacePercent = ref(0)
const spaceCurrent = ref('0 B')
const spaceTotal = ref('0 B')
const recShow = ref(false)
const checkedRecAll = ref(false)
const select_rec_list = ref([])
const inverseRec = ref(false)
const inverse = ref(false)
const addBtnFlag = ref(true)
const backupStatus = ref(false)
const leftNewTreeId = ref('treeDemo')
const leftFolderId = ref('')
const currentShowFlag = ref('')
const createFolderVisible = ref(false)
const folderNameForm = ref({ folderNameSelf: '' })
const httpPath = ref('/api')
const cropId = ref('')
const oldName = ref('') // 存储原始文件名
const blurStatus = ref(false) // 重命名失焦状态
const subId = ref('')
const yunUid = ref('')
const permDownload = ref(true) // 下载权限控制变量



// 预览相关响应式数据
const dialogPreviewVideo = ref(false)
const dialogPreviewImg = ref(false)
const fileMetaDialogFlag = ref(false)
const videoUrl = ref('')
const dialogImgurl = ref('')
const fileFormat = ref('')
const playList = ref([])
const fid = ref('')
const picInfo = ref({})
const fileMetaObj = ref({})
const dialogFormVisible = ref(false)
// 右键菜单相关数据
const contextMenuVisible = ref(false)
const contextMenuX = ref(0)
const contextMenuY = ref(0)
const currentItem = ref({})
const currentIndex = ref(0)
const transferIndex = ref(0)
const menuItems = ref([]) // 右键菜单列表

// 新增的响应式数据
const devicesExpanded = ref(false)
const showRecycleView = ref(false)
const currentViewType = ref('folder') // 'folder', 'device', 'recycle'
const deviceList = ref([])
// 初始化回收站数据
const recycleList = ref([])

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 搜索分页相关数据
const searchPage = reactive({
  currentPage: 1,
  numPerPages: 10,
  total: 0
})

// 分页计算属性
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allDataList.value.slice(start, end)
})

// 分页变化处理函数
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  console.log('分页变化',val)
  getRightList() // 调用数据加载函数，而不是仅更新本地显示
}

const handleCurrentChange = (val) => {
  console.log('页变化',val)
  currentPage.value = val
  getRightList() // 调用数据加载函数，而不是仅更新本地显示
}

// 搜索分页处理函数
const searchHandleSizeChange = (val) => {
  searchPage.numPerPages = val
  searchPage.currentPage = 1
  console.log('searchHandleSizeChange',val)
  searchBtn()
}

const searchHandleCurrentChange = (val) => {
  searchPage.currentPage = val
  console.log('searchHandleCurrentChange',val)
  searchBtn()
}

// 根据当前页更新显示列表
const updateRightListByPage = () => {
  rightList.value = currentPageData.value.map(item => ({
    ...item,
    checked: false,
    currentShowFlag: '0',
    unbind: false
  }))
  selectedList.value = []
  checkedAll.value = false
}

// 组件引用
const uploadChild = ref(null)
const selectFileNewTree = ref(null)

// 方法
const uploadPathFn = () => {
  // 与Vue2版本保持一致的简化实现
  getRightList()
}

// 处理文件夹创建成功
const folderCreatedEmit = () => {
  // 与Vue2版本保持一致
  folderCreatedCast.value = false
}

// 处理文件夹创建成功的新方法 - 简化版本
const handleFolderCreatedEmit = async () => {
  folderCreatedCast.value = true;
  try {
      // 使用组件内的paths变量，而不是从sessionStorage读取
      const currentPath = paths.value || '';      
      // 重新获取数据
      console.log('刷新列表',currentPath)
      const res = await asyncGetData("getlist", currentPath, currentPage.value, pageSize.value, sortTypeNumber.value, orderStyle.value);
      
      // 按照getRightList的标准流程更新数据
      if (res.code == 200 && res.data) {
        // 先更新allDataList，这是正确的数据源
        allDataList.value = [];
        allDataList.value = allDataList.value.concat(res.data);
        console.log('刷新列表数据:', allDataList.value);
        
        // 然后通过updateRightListByPage更新视图显示
        updateRightListByPage();
        computePage();
      }
    } catch (error) {
      console.error('刷新列表失败:', error);
    } finally {
      // 重置状态
      setTimeout(() => {
        folderCreatedCast.value = false;
      }, 500);
  }
}

// 触发文件上传


// Vue2风格的事件处理函数
const clickInfoFn = (val) => {
  folderShow.value = val.folderShow || true
  leftFolderId.value = val.treeClickNum || ''
  currentPage.value = 1
  
  if (currentViewType.value !== 'folder') {
    currentViewType.value = 'folder'
  }
}

const leftTreeLoadingFn = (val) => {
  leftTreeLoading.value = val
}

const backupStatusFn = (val) => {
  backupStatus.value = val
}

const backflagFn = (val) => {
  backflag.value = val
}

const treeClickNumFn = (val) => {
  leftFolderId.value = val
}

const updateFileList = (val) => {
  // 更新paths变量，这是Vue2联动的关键
  if (val.path && val.path !== '我的空间') {
    paths.value = val.path
  } else {
    paths.value = ''
  }
  
  // 根据路径决定调用哪个方法获取文件列表
  if (!val.path || val.path === '我的空间' || val.path === '') {
    getFolderList()
  } else {
    getRightList()
  }
}

const publicPathFnLeftTree = (path) => {
  // 重置为文件夹视图
  currentViewType.value = 'folder'
  showRecycleView.value = false
  
  // 更新paths变量 - 与Vue2保持一致
  if (path && path !== '我的空间') {
    paths.value = path
    
    // 更新面包屑列表
    const pathParts = path.split('/')
    crumbList.value = [...pathParts].filter(Boolean)
    
    // 调用getRightList更新右侧列表
    getRightList()
  } else {
    paths.value = ''
    crumbList.value = []
    getFolderList()
  }
  
  // 保存路径到sessionStorage
  window.sessionStorage.setItem('pathLocal', paths.value || '')
  
  if (!path || path === '' || path === '我的空间') {
    // 根目录处理
    backflag.value = false
    crumbList.value = []
    
    // 获取根目录文件列表
    getFolderList()
  } else {
    // 子目录处理
    paths.value = path
    backflag.value = true
    
    // 更新面包屑导航
    const pathParts = path.split('/').filter(Boolean)
    crumbList.value = [...pathParts]
    
    // 获取文件列表
    getRightList()
  }
}

// 挂载设备相关函数
const showDeviceList = async () => {
  currentViewType.value = 'device'
  showRecycleView.value = false
  devicesExpanded.value = false
  rightOperateLoading.value = true
  
  try {
    // 调用实际API获取设备列表
    const response = await getDeviceList()
    
    // 检查响应数据结构
    if (response && response.status === 200 && response.data && response.data.list) {
      deviceList.value = response.data.list.map(item => ({
        id: item.id,
        name: item.name,
        ip: item.ip || '',
        path: item.path || '',
        status: item.status || '离线',
        capacity: item.capacity || '0GB/0GB',
        available: item.available || '0GB',
        createTime: item.create_time || new Date().toLocaleString()
      }))
    }
  } catch (error) {
    ElMessage.error('获取设备列表失败，请重试')
  } finally {
    rightOperateLoading.value = false
  }
}

// 获取空间信息
const getSpaceData = async () => {
  try {
    const response = await getSpaceInfo()
    if (response && response.status === 200 && response.data) {
      const data = response.data
      // 更新空间信息变量
      spacePercent.value = calculateSpacePercent(data.used || 0, data.total || 0)
      spaceCurrent.value = formatFileSize(data.used || 0)
      spaceTotal.value = formatFileSize(data.total || 0)
    }
  } catch (error) {
    ElMessage.error('获取空间信息失败，请重试')
  }
}

// 回收站相关函数
const showRecycleBin = async () => {
  showRecycleView.value = true
  currentViewType.value = 'recycle'
  devicesExpanded.value = false
  rightOperateLoading.value = true
  
  try {
    // 调用实际API获取回收站数据
    const response = await getRecycleBinList()
    
    // 检查响应数据结构
    if (response && response.status === 200 && response.data && response.data.list) {
      recycleList.value = response.data.list.map(item => ({
        id: item.fid || item.id,
        name: item.name,
        size: formatFileSize(item.fsize || 0),
        deleteTime: item.dtime || item.ctime || new Date().toLocaleString(),
        path: item.path || '',
        checked: false
      }))
    }
  } catch (error) {
    ElMessage.error('获取回收站数据失败，请重试')
  } finally {
    rightOperateLoading.value = false
  }
}

const mySpaceClick = () => {
  paths.value = ''
  currentViewType.value = 'folder' // 确保切换到文件夹视图
  backflag.value = false
  crumbList.value = []
  currentPage.value = 1 // 重置页码为1
  
  // 调用FileTree组件的dataInitProcess1方法，与Vue2版本保持一致
  if (selectFileNewTree.value) {
    selectFileNewTree.value.dataInitProcess1()
  }
  
  // 获取根目录文件列表
  getFolderList()
  
  // 保存路径到sessionStorage
  window.sessionStorage.setItem('pathLocal', paths.value)
}

const breadClick = (item) => {
  // 过滤空字符串并处理路径
  const curentsPathArr = paths.value.split('/').filter(Boolean)
  const curentIndex = curentsPathArr.indexOf(item) + 1
  const curentArr = curentIndex > 0 ? curentsPathArr.slice(0, curentIndex) : []
  crumbList.value = [...curentArr]
  const newPath = curentArr.join('/')
  paths.value = newPath
  
  // 设置backupStatus为true，防止折叠其他节点
  backupStatus.value = true
  
  // 页码重置为1
  currentPage.value = 1
  
  // 更新视图类型为文件夹
  currentViewType.value = 'folder'
  
  if (paths.value === '') {
    // 回到根目录时的处理
    backflag.value = false
    
    // 调用FileTree组件的dataInitProcess1方法
    if (selectFileNewTree.value) {
      selectFileNewTree.value.dataInitProcess1()
    }
    
    getFolderList()
  } else {
    // 在子目录中时的处理
    backflag.value = true
    
    // 通知FileTree组件路径更新
    if (selectFileNewTree.value) {
      // 触发publicPath事件，模拟Vue2的行为
      publicPathFnLeftTree(paths.value)
    }
    
    getRightList()
  }
  
  // 保存路径到sessionStorage
  window.sessionStorage.setItem('pathLocal', paths.value)
}


const backUpClick = () => {
  // 设置backupStatus为true，防止折叠其他节点
  backupStatus.value = true
  
  // 页码重置为1
  currentPage.value = 1
  
  // 更新视图类型为文件夹
  currentViewType.value = 'folder'
  
  if (paths.value) {
    const lastIndex = paths.value.lastIndexOf('/')
    paths.value = lastIndex > 0 ? paths.value.substring(0, lastIndex) : ''
    
    if (paths.value === '') {
      // 回到根目录时的处理
      backflag.value = false
      
      // 调用FileTree组件的dataInitProcess1方法，与Vue2版本保持一致
      if (selectFileNewTree.value) {
        selectFileNewTree.value.dataInitProcess1()
      }
      
      getFolderList()
    } else {
      // 在子目录中时的处理
      backflag.value = true
      
      // 通知FileTree组件路径更新
      if (selectFileNewTree.value) {
        // 触发publicPath事件，模拟Vue2的行为
        publicPathFnLeftTree(paths.value)
      }
      
      getRightList()
    }
    
    // 强制更新crumbList - 过滤空字符串
    const pathParts = paths.value.split('/').filter(Boolean)
    crumbList.value = [...pathParts]
  }
  
  // 保存路径到sessionStorage
  window.sessionStorage.setItem('pathLocal', paths.value)
}

const getFolderList = async () => {
  searchShow.value = false
  initRecAllCheckVar()
  recShow.value = false
  rightOperateLoading.value = true
  
  // 清除pid，根目录没有父级ID
  sessionStorage.removeItem('pidFolder')
  
  // 重置页码为1
  currentPage.value = 1
  
  try {
    // 调用asyncGetFolderList获取外层目录结构
    const res = await asyncGetFolderList()
    
    if (res && res.code === 200) {
      rightOperateLoading.value = false
      // 清空并重新填充数据
      allDataList.value = []
      allDataList.value = allDataList.value.concat(res.data)
      updateRightListByPage()
      computePage()
      
      // 重置选择状态
      allDataList.value.forEach(item => { item.checked = false })
      selectedList.value = []
      checkedAll.value = false
      navBtnShow.value = false
      
      // 保存路径到sessionStorage
      window.sessionStorage.setItem('pathLocal', paths.value)
    } else {
      rightOperateLoading.value = false
    }
  } catch (error) {
    rightOperateLoading.value = false
  }
}

// 初始化回收站变量
const initRecAllCheckVar = () => {
  checkedRecAll.value = false
  select_rec_list.value = []
  inverseRec.value = false
}

// 高度自适应计算
const computePage = () => {
  const rightHeightTarget = document.getElementsByClassName('folder-right-operate')[0];
  const leftTree = document.getElementsByClassName('left-tree')[0];
  const requireHeight = `height:${window.innerHeight - 80}px;` //外层容器
  const requireLeftHeight = `height:${window.innerHeight - 140}px;`
  const innerHeightBox = document.querySelector('.right-list-container') //inner
  
  if (rightHeightTarget) rightHeightTarget.style = requireHeight;
  if (leftTree) leftTree.style = requireLeftHeight;
  if (innerHeightBox) innerHeightBox.style = `max-height:${(window.innerHeight - 160) * 0.9}px;` //下方区域留白
}

const getRightList = async () => {
  searchShow.value = false
  initRecAllCheckVar()
  recShow.value = false
  rightOperateLoading.value = true
  
  // 路径处理 - 确保path参数格式正确
  const currentPath = paths.value || ''
  
  // 使用当前页码，不再强制重置为1
  
  try {
    // 调用asyncGetData获取文件列表
    const response = await asyncGetData('getlist', currentPath, currentPage.value, pageSize.value, sortTypeNumber.value, orderStyle.value)
    
    if (response && response.code === 200) {
      rightOperateLoading.value = false
      
      const totalNum = parseInt(response.totalnum) || 0
      total.value = totalNum
      
      // 清空并重新填充数据
      allDataList.value = []
      const dataToAdd = response.data || []
      allDataList.value = allDataList.value.concat(dataToAdd)
      
      // 更新分页显示和计算页面高度
      updateRightListByPage()
      computePage()
      
      // 重置选择状态
      if (rightList.value && Array.isArray(rightList.value)) {
        rightList.value.forEach((item, index) => {
          item.checked = false
          // 只设置第一个项目的pid到sessionStorage
          if (index === 0 && item.pid) {
            sessionStorage.setItem('pidFolder', item.pid)
          }
        })
      }
      
      selectedList.value = []
      checkedAll.value = false
      navBtnShow.value = true
      
      // 保存路径到sessionStorage
      window.sessionStorage.setItem('pathLocal', currentPath)
    } else {
      rightOperateLoading.value = false
    }
  } catch (error) {
    rightOperateLoading.value = false
  } finally {
    // 函数调用结束
  }
}

const sortSelf = async (type, name) => {
  sorttypeName.value = name
  sortTypeNumber.value = type === 'name' ? '7' : type === 'fsize' ? '6' : type === 'ctime' ? '5' : ''
  orderStyle.value = name.includes('up') ? '1' : '2'
  await getRightList()
}

const checkAll = () => {
  rightList.value.forEach(item => {
    item.checked = checkedAll.value
  })
  updateSelectedList()
}

const singleSelect = (item) => {
  updateSelectedList()
  checkedAll.value = rightList.value.every(item => item.checked)
}

const updateSelectedList = () => {
  selectedList.value = rightList.value.filter(item => item.checked)
}

// 导入相关的API函数
import {
  asyncDeleteFile, 
  asyncDeleteFolder,
  asyncMoveFile,
  asyncCopyFolder,
  asyncMoveFolder,
  fileDown
} from '../api/fileManage'

// 复制相关变量
const switchFlagCopyAll = ref(false)
const selectFileCopyAll = ref(null)
const selectDialogCopy = ref('')
const copyList = ref([])

// 移动相关变量
const switchFlagMoveAll = ref(false)
const selectFileMoveAll = ref(null)
const selectDialog = ref('')
const moveList = ref([])

// 删除文件或文件夹
const deleteAll = () => {
  // 与Vue2版本保持一致
  if (!permUpload.value) {
    ElMessageBox.confirm('您没有权限删除，请联系管理员', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: ''
    })
    return
  }
  
  ElMessageBox.confirm('确认删除吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: ''
  }).then(() => {
    let currentIndex = 0;
    const currentPath = paths.value || '';
    
    // 按照Vue2版本的逻辑实现
    selectedList.value.forEach(v => {
      if (v.filetype !== '0' && v.filetype !== '6') {
        // 删除文件
        asyncDeleteFile("delete", v.fid, currentPath, v.name, v.pid, v.nodeid).then(res => {
          if (res.code == 200) {
            currentIndex++
            if (currentIndex == selectedList.value.length) {
              selectedList.value = []
              ElMessage.success('操作成功')
              getRightList()
            }
          } else {
            ElMessage.error(res.msg);
            // 刷新树结构
            if (selectFileNewTree.value) {
              selectFileNewTree.value.dataInitProcess1();
            }
          }
        }).catch(() => {
          ElMessage.error('操作失败')
        })
      } else {
        // 删除文件夹
        asyncDeleteFolder("delete", currentPath, v.name, v.pid, v.nodeid).then(res => {
          if (res.code == 200) {
            currentIndex++
            if (currentIndex == selectedList.value.length) {
              selectedList.value = []
              ElMessage.success('操作成功')
              // 删除文件夹后需要刷新树结构
              if (selectFileNewTree.value) {
                selectFileNewTree.value.dataInitProcess1();
              }
              getRightList()
            }
          } else {
            ElMessage.error(res.msg);
            // 刷新树结构
            if (selectFileNewTree.value) {
              selectFileNewTree.value.dataInitProcess1();
            }
          }
        }).catch(() => {
          ElMessage.error('操作失败')
        })
      }
    })
  }).catch(() => {})
}
  
// 批量移动--(加载文件选择器)
const moveAllSelect = () => {
  if (selectedList.value.length === 0) {
    ElMessage.warning('请选择要移动的文件')
    return
  }
  switchFlagMoveAll.value = true
  if (selectFileMoveAll.value) {
    selectFileMoveAll.value.dataInitProcess1()
  }
}

/**
 * 批量复制--确定
 * @param {String} val //新路径
 */
const copyAll = (val) => {
  const oldpath = paths.value || ''
  selectDialogCopy.value = val
  let currentIndex = 0
  
  selectedList.value.forEach(async (v) => {
    if (currentIndex > selectedList.value.length) {
      return
    }
    
    if (v.filetype !== '0' && v.filetype !== '6') {
      // 复制文件
      asyncMoveFile("copy", v.name, selectDialogCopy.value, oldpath, v.fid).then(res => {
        if (res.code == 200) {
          currentIndex++
          if (currentIndex == selectedList.value.length) {
            selectedList.value = []
            ElMessage.success('操作成功')
            getRightList()
          }
        } else {
          ElMessage.error(res.msg)
        }
      }).catch(() => {
        ElMessage.error('操作失败')
      })
    } else {
      // 复制文件夹
      try {
        const copyFolderRes = await asyncCopyFolder('copy', v.name, selectDialogCopy.value, oldpath)
        if (copyFolderRes.code == '200') {
          const searchListRes = await asyncGetData("getlist", selectDialogCopy.value)
          if (searchListRes.code == '200') {
            copyList.value = []
            copyList.value = copyList.value.concat(searchListRes.data)
            
            currentIndex++
            if (currentIndex == selectedList.value.length) {
              selectedList.value = []
              ElMessage.success('操作成功')
              if (selectFileNewTree.value) {
                selectFileNewTree.value.dataInitProcess1()
              }
              getRightList()
            }
          }
        } else {
          ElMessage.error(copyFolderRes.msg)
          if (selectFileNewTree.value) {
            selectFileNewTree.value.dataInitProcess1()
          }
          getRightList()
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

/**
 * 批量移动
 * @param {String} val
 */
const moveAll = (val) => {
  const oldpath = paths.value || ''
  let currentIndex = 0
  selectDialog.value = val
  
  selectedList.value.forEach(async (v) => {
    if (currentIndex > selectedList.value.length) {
      return
    }
    
    if (v.filetype !== '0' && v.filetype !== '6') {
      // 移动文件
      asyncMoveFile("move", v.name, selectDialog.value, oldpath, v.fid).then(res => {
        if (res.code === 200) {
          currentIndex++
          if (currentIndex == selectedList.value.length) {
            selectedList.value = []
            ElMessage.success('操作成功')
            getRightList()
          }
        } else {
          ElMessage.error(res.msg)
          getRightList()
        }
      }).catch(() => {
        ElMessage.error('操作失败')
      })
    } else {
      // 移动文件夹
      try {
        const moveFolderRes = await asyncMoveFolder('move', v.name, selectDialog.value, oldpath)
        if (moveFolderRes.code == 200) {
          const searchListRes = await asyncGetData("getlist", oldpath)
          if (searchListRes.code == '200') {
            moveList.value = []
            moveList.value = moveList.value.concat(searchListRes.data)
            
            currentIndex++
            if (currentIndex == selectedList.value.length) {
              selectedList.value = []
              ElMessage.success('操作成功')
              if (selectFileNewTree.value) {
                selectFileNewTree.value.dataInitProcess1()
              }
              getRightList()
            }
          }
        } else {
          ElMessage.error(moveFolderRes.msg)
          if (selectFileNewTree.value) {
            selectFileNewTree.value.dataInitProcess1()
          }
          getRightList()
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 下载功能
const downRightClick = async (item, index) => {
  // 打印调用信息和选中的文件列表
  console.log('downRightClick调用 - item信息:', item);
  console.log('downRightClick调用 - index信息:', index);
  console.log('当前选中文件数量:', selectedList.value.length);
  console.log('选中文件列表:', selectedList.value);
  
  // 首先检查下载权限
  if (!permDownload.value) {
    ElMessageBox.confirm('您没有下载权限，请联系管理员', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: ''
    })
    return
  }
  
  // 定义通用下载函数
  const fileDownFn = (fid, name) => {
    console.log('fileDownFn调用 - fid:', fid,'name',name);   
    fileDown(fid, name).then(response => {
      console.log('完整响应对象:', response);
      
      // 尝试两种响应格式，优先检查response.url，然后检查response.data.url
      let downloadUrl = null;
      if (response && response.url) {
        downloadUrl = response.url;
        console.log('直接从response获取url:', downloadUrl);
      } else if (response && response.data && response.data.url) {
        downloadUrl = response.data.url;
        console.log('从response.data获取url:', downloadUrl);
      }
      
      if(downloadUrl){
        // a链接后端流方案
        let a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        a.href = downloadUrl;
        a.download = name;
        a.click();
        a.remove();
        window.URL.revokeObjectURL(downloadUrl);
      } else {
        console.error('无法获取下载链接:', response);
        ElMessage.error('获取下载链接失败');
      }
    }).catch(res => {
      console.error('下载请求失败:', res);
      ElMessage.error('下载请求失败，请重试');
    })
  }
  
  // 情况1：从下载按钮调用（不传参数或传入事件对象）- 执行批量下载
  if (!item || item instanceof MouseEvent || item instanceof PointerEvent) {
    if (selectedList.value.length === 0) {
      ElMessage.error('请选择要下载的文件');
      return;
    }
    
    // 过滤出可下载的文件（非文件夹）
    const downloadableFiles = selectedList.value.filter(file => file && file.filetype !== "0");
    
    if (downloadableFiles.length === 0) {
      ElMessage.warning('选中的项目中没有可下载的文件（文件夹无法下载）');
      return;
    }
    
    ElMessage.success(`开始下载 ${downloadableFiles.length} 个文件...`);
    
    // 批量下载选中的文件
    for(let i = 0; i < downloadableFiles.length; i++){
      ((a) => {
        setTimeout(() => {
          const selectedItem = downloadableFiles[a];
          console.log(`正在下载文件 ${a+1}/${downloadableFiles.length}:`, selectedItem.name);
          fileDownFn(selectedItem.fid, selectedItem.name);
        }, 1000 * a);
      })(i)
    }
  }
  // 情况2：从右键菜单调用（传入文件对象）- 单文件下载
  else if (item && typeof item === 'object' && 'fid' in item) {
    // 关闭右键菜单
    contextMenuVisible.value = false;
    // 确保不是文件夹才下载
    if (item.filetype === "0") {
      ElMessage.error('无法下载文件夹');
      return;
    }
    // 单个文件下载
    console.log('右键菜单下载文件:', item.name);
    fileDownFn(item.fid, item.name);
  }
  else {
    // 其他情况 - 如果selectedList有内容，仍然尝试批量下载
    if (selectedList.value.length > 0) {
      ElMessage.success(`开始下载 ${selectedList.value.length} 个文件...`);
      
      // 过滤出可下载的文件
      const downloadableFiles = selectedList.value.filter(file => file && file.filetype !== "0");
      
      for(let i = 0; i < downloadableFiles.length; i++){
        ((a) => {
          setTimeout(() => {
            const selectedItem = downloadableFiles[a];
            fileDownFn(selectedItem.fid, selectedItem.name);
          }, 1000 * a);
        })(i)
      }
    } else {
      ElMessage.error('请选择要下载的文件');
    }
  }
}


// 批量复制--(加载文件选择器)
const copyAllSelect = () => {
  if (selectedList.value.length === 0) {
    ElMessage.warning('请选择要复制的文件')
    return
  }
  switchFlagCopyAll.value = true
  if (selectFileCopyAll.value) {
    selectFileCopyAll.value.dataInitProcess1()
  }
}

  

// 单次勾选--重命名
const renameBtn = () => {
  if (selectedList.value.length !== 1) {
    ElMessage.warning('请选择单个文件进行重命名')
    return
  }
  selectedList.value.forEach(v => {
    // 使用响应式方式设置属性
    Object.assign(v, {
      currentShowFlag: '1',
      unbind: true
    })
    blurStatus.value = true
    setTimeout(() => {
      const inputElement = document.getElementById('inputMark')
      if (inputElement) {
        inputElement.focus()
      }
    }, 100)
    oldName.value = v.name
  })
}

const recoveryAllSelect = async () => {
  if (select_rec_list.value.length === 0) {
    ElMessage.warning('请选择要恢复的文件')
    return
  }
  
  try {
    let currentIndex = 0
    const totalItems = select_rec_list.value.length
    
    for (const v of select_rec_list.value) {
      const res = await asyncGetRecDel("recovery", v.name, v.nodeid, v.fid, '0')
      const data = res.data
      if (data.code === 200) {
        currentIndex++
        if (currentIndex === totalItems) {
          select_rec_list.value = []
          ElMessage.success('操作成功')
          getFileDescRec() // 刷新回收站列表
        }
      } else {
        ElMessage.error(data.msg)
        break
      }
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const completeDeleAll = async () => {
  if (select_rec_list.value.length === 0) {
    ElMessage.warning('请选择要彻底删除的文件')
    return
  }
  
  try {
    let currentIndex = 0
    const totalItems = select_rec_list.value.length
    
    for (const v of select_rec_list.value) {
      const res = await asyncGetRecDel("delete", v.name, v.nodeid, v.fid, '0')
      const data = res.data
      if (data.code === 200) {
        currentIndex++
        if (currentIndex === totalItems) {
          select_rec_list.value = []
          ElMessage.success('操作成功')
          getFileDescRec() // 刷新回收站列表
        }
      } else {
        ElMessage.error(data.msg)
        break
      }
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const searchChange = () => {
  // 搜索类型改变
}

const searchBtn = () => {
  // 与Vue2版本保持一致
  searchShow.value = true
  if (!search.word) {
    searchShow.value = false
    getRightList()
    return
  }
  
  // 根据搜索类型区分处理
  if (search.key === '1') {
    // fid搜索
    rightOperateLoading.value = true
    // 这里应该调用searchFid接口，暂时保留模拟实现
    
    // 模拟搜索结果
    setTimeout(() => {
      rightOperateLoading.value = false
      allDataList.value = []
      // 实际应该根据接口返回数据填充
      updateRightListByPage()
      computePage()
    }, 300)
  } else {
    // 文件名搜索，保持原有的asyncGetData调用
    rightOperateLoading.value = true
    asyncGetData('search', '', 1, pageSize.value, '', '', search.word).then(response => {
      rightOperateLoading.value = false
      
      let searchResult = []
      if (response && response.status === 200 && response.data && response.data.list) {
        searchResult = response.data.list.map(item => ({
          id: item.fid || item.id,
          name: item.name,
          filetype: item.filetype,
          fsize: item.fsize || 0,
          ctime: item.upload_time || item.create_time || new Date().toLocaleString(),
          mtime: item.update_time || new Date().toLocaleString(),
          path: item.path || ''
        }))
      }
      
      total.value = response.data.total || searchResult.length
      allDataList.value = searchResult
      currentPage.value = 1
      updateRightListByPage()
    }).catch(() => {
      rightOperateLoading.value = false
    })
  }
    

}

const childNodeClick = (item) => {
  // 重置页码数据
  currentPage.value = 1;
  
  const isFolder = item.filetype === FileType.FOLDER.toString() || item.filetype === FileType.HIDE_DIRECTORY.toString()
  
  if (isFolder) {
    // 点击文件夹 - 与Vue2版本保持一致
    if (searchShow.value) {
      paths.value = item.path || ''
    } else {
      if (paths.value !== '') {
        const newPath = `${paths.value}/${item.name}`.replace(/\/\//g, '/')
        paths.value = newPath
      } else {
        paths.value = item.name
      }
    }
    
    // 更新面包屑列表
    const pathParts = paths.value.split('/')
    crumbList.value = [...pathParts].filter(Boolean)
    
    // 设置返回按钮状态
    backflag.value = true
    
    // 保存路径到sessionStorage
    window.sessionStorage.setItem('pathLocal', paths.value)
    
    // 获取右侧文件列表
    getRightList()
  } else {
    // 点击文件，根据类型预览
    if (item.filetype === FileType.IMAGE.toString()) {
      openImagePreview(item)
    } else if (item.filetype === FileType.VIDEO.toString()) {
      openVideoPreview(item)
    } else {
      showFileMeta(item)
    }
  }
}

const showMenu = (item, index, filetype) => {
  // 设置当前选中项
  currentItem.value = item
  currentIndex.value = index
  transferIndex.value = index
  
  // 设置右键菜单位置
  contextMenuX.value = event.clientX
  contextMenuY.value = event.clientY
  
  // 构建菜单
  let items = []    // 根据文件类型过滤菜单
  if (permUpload.value) {
    // 有权限才显示这些菜单项
    items.unshift({ label: '重命名', action: 'rename' })
    items.push(
      { label: '移动', action: 'move' },
      { label: '复制', action: 'copy' },
      { label: '删除', action: 'delete'} 
    )
  }
  if (filetype !== "0" && filetype !== "6") {
    // 非文件夹添加下载和文件元数据菜单项
    items.push(
      { label: '下载', action: 'download' },
      { label: '查看详情', action: 'filemeta' }
    )
  }  
  // 设置右键菜单列表并显示
  menuItems.value = items
  contextMenuVisible.value = true
}

// 右键菜单点击处理
const handleContextMenuClick = (item) => {
  switch (item.action) {
    case 'rename':
      renameRightClick(currentItem.value, currentIndex.value)
      break
    case 'delete':
      deleteRightClick(currentItem.value, currentIndex.value)
      break
    case 'newfolder':
      newRightClickDialog(currentItem.value, currentIndex.value)
      break
    case 'download':
      downRightClick(currentItem.value, currentIndex.value)
      break
    case 'move':
      moveRightClick(currentItem.value, currentIndex.value)
      break
    case 'copy':
      copyRightClick(currentItem.value, currentIndex.value)
      break
    case 'filemeta':
      fileMetaClick(currentItem.value, currentIndex.value)
      break
  }
}

// 右键菜单项对应的处理函数
const renameRightClick = (item, index) => {
  // 与Vue2版本保持一致，直接在文件名处修改
  Object.assign(item, {
    currentShowFlag: '1',
    unbind: true
  })
  blurStatus.value = true
  setTimeout(() => {
    const inputElement = document.getElementById('inputMark')
    if (inputElement) {
      inputElement.focus()
    }
  }, 100)
  oldName.value = item.name
  contextMenuVisible.value = false // 关闭右键菜单
}

const deleteRightClick = (item, index) => {
  // 清空选中列表，添加当前项，然后调用批量删除函数
  selectedList.value = [item];
  // 关闭右键菜单
  contextMenuVisible.value = false;
  // 调用导航栏中的删除函数
  deleteAll();
}

const newRightClickDialog = (item, index) => {
  // 与Vue2版本保持一致
  folderNameForm.value = { folderNameSelf: '' };
  createFolderVisible.value = true;
  // 关闭右键菜单
  contextMenuVisible.value = false;
}

const moveRightClick = (item, index) => {
  // 清空选中列表，添加当前项，然后调用批量移动函数
  selectedList.value = [item];
  // 关闭右键菜单
  contextMenuVisible.value = false;
  // 调用导航栏中的移动函数
  moveAllSelect();
}

const copyRightClick = (item, index) => {
  // 清空选中列表，添加当前项，然后调用批量复制函数
  selectedList.value = [item];
  // 关闭右键菜单
  contextMenuVisible.value = false;
  // 调用导航栏中的复制函数
  copyAllSelect();
}

const fileMetaClick = (item, index) => {
  // 关闭右键菜单
  contextMenuVisible.value = false;
  showFileMeta(item)
}

const dbclickOpen = (item) => {
  childNodeClick(item)
}

// 预览相关方法
const openImagePreview = (item) => {
  dialogPreviewImg.value = true
  dialogImgurl.value = `${httpPath.value}/file/view/${item.fid}`
  picInfo.value = {
    name: item.name,
    size: formatFileSize(item.fsize),
    width: '1920', // 模拟数据
    height: '1080', // 模拟数据
    format: item.name.split('.').pop().toLowerCase(),
    createTime: item.ctime
  }
}

const openVideoPreview = (item) => {
  dialogPreviewVideo.value = true
  videoUrl.value = `${httpPath.value}/file/view/${item.fid}`
  fileFormat.value = item.name.split('.').pop().toLowerCase()
  fid.value = item.fid
  
  // 获取同类型文件作为播放列表
  playList.value = rightList.value
    .filter(file => file.filetype === FileType.VIDEO.toString())
    .map(file => ({
      id: file.fid,
      name: file.name,
      url: `${httpPath.value}/file/view/${file.fid}`
    }))
}

const showFileMeta = (item) => {
    asyncfileMeta(item.fid).then(res => {
      fileMetaObj.value = res
      console.log('文件元数据:', fileMetaObj.value)
      fileMetaDialogFlag.value = true
    })
  }

const getFileTypeLabel = (type) => {
  const typeMap = {
    '0': '文件夹',
    '1': '文档',
    '2': '图片',
    '3': '普通文件',
    '4': '音频',
    '5': '压缩包',
    '6': '隐藏目录',
    '7': '视频'
  }
  return typeMap[type] || '未知类型'
}

// 预览对话框关闭处理
const handleCloseVideo = () => {
  dialogPreviewVideo.value = false
}

const handleCloseImg = () => {
  dialogPreviewImg.value = false
  fileMetaDialogFlag.value = false
}

const flashClick = () => {
  ElMessage.info('刷新视频源')
}

const handleOpen = () => {
  // 处理打开文件
}

const curentVideo = () => {
  // 处理当前视频
}

const removePrevItem = (index) => {
  // 移除之前的选中项
}

const modifyNameClick = () => {
  // 修改名称
}

const blurEvent = (item) => {
  item.currentShowFlag = '0'
  item.unbind = false
  
  const oldNameValue = oldName.value
  const newName = item.name
  const nodeid = item.nodeid
  const paths = window.sessionStorage.getItem('pathLocal')
  const fids = item.fid
  
  // 判断是文件夹还是文件
  if (item.filetype == '0') {
    // 调用文件夹重命名API
    asyncRenameFolder("rename", oldNameValue, newName, nodeid, paths).then(res => {
      if (res.code == 200) {
        blurStatus.value = false
        ElMessage.success("操作成功")
        getRightList()
        if (selectFileNewTree.value) {
          selectFileNewTree.value.dataInitProcess1()
        }
      } else {
        blurStatus.value = false
        ElMessage.error(res.msg)
        getRightList()
      }
    })
  } else {
    // 调用文件重命名API
    asyncRenameFile("rename", oldNameValue, newName, fids, paths).then(res => {
      if (res.code == 200) {
        blurStatus.value = false
        ElMessage.success("操作成功")
        getRightList()
      } else {
        blurStatus.value = false
        ElMessage.error(res.msg)
        getRightList()
      }
    })
  }
}

const searchFolderClick = (path) => {
  // 搜索结果中的文件夹点击
  paths.value = path
  crumbList.value = [...paths.value.split('/')]
  searchShow.value = false
  getRightList()
}

const checkRecAll = () => {
  recycleList.value.forEach(item => {
    item.checked = checkedRecAll.value
  })
}

const singleRecSelect = (item) => {
  checkedRecAll.value = recycleList.value.every(item => item.checked)
}

/**
 * 回收站节点点击处理函数 - 与Vue 2版本getFileDescRec保持命名和功能一致
 * @param {Object} treeNode - 树节点对象
 */
const getFileDescRec = async () => {
  // 初始化批量文件变量
  initAllCheckVar()
  folderShow.value = false
  recShow.value = true
  
  try {
    const res = await asyncGetRecList('getlist')
    if (res.code === "200") {
      recycleList.value = []
      recycleList.value = recycleList.value.concat(res.data)
      // 按时间倒序排序
      recycleList.value.sort((a, b) => new Date(b.dtimer) - new Date(a.dtimer))
      
      // 初始化选中状态
      recycleList.value.forEach(v => {
        v.checked = false
      })
      select_rec_list.value = []
      checkedRecAll.value = false
      computePage()
    } else {
      recycleList.value = []
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const routerPathOk = () => {
  // 路由路径确认
}

// formatFileSize函数已从fileUtils.js导入，这里移除本地实现

// 生命周期
onMounted(async () => {
    getFolderList()
    
    // 调用getSpaceData函数获取空间信息
    getSpaceData()
    
    // 添加右键菜单事件监听
    document.addEventListener('contextmenu', (e) => {
      if (e.target.closest('.right-list-item')) {
        contextMenuX.value = e.clientX
        contextMenuY.value = e.clientY
      }
    })
  })

onUnmounted(() => {
  // 清理事件监听器
  document.removeEventListener('contextmenu', () => {})
})
</script>

<style scoped>
/* 重命名输入框样式 */
:deep(#inputMark) {
  width: auto;
  min-width: 150px;
  padding: 2px 4px;
  border: 1px solid #409eff;
  border-radius: 4px;
  outline: none;
  font-size: 14px;
}

.file-manage-container {
  width: 100%;
  height: 100%;
}

.file-bread {
  background: #fff;
  padding: 10px 20px;
  border-bottom: 1px solid #e9edf6;
}

.bread-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-l {
  flex: 1;
}

.header-nav-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.flexs-layout {
  display: flex;
  align-items: center;
}

.btn-box {
  display: flex;
  align-items: center; 
}

.search-boxs {
  display: flex;
  align-items: center;
}

.search-boxs .item {
  margin-right: 5px;
}

.main-common {
  padding: 10px;
  background: #f1f3f7;
  height: calc(100vh - 60px);
}

.main {
  display: flex;
  height: 100%;
}

.main-items {
  background: #fff;
  border-radius: 4px;
  padding: 10px;
  overflow: hidden;
}

.left-parts {
  flex: 0 0 250px;
  margin-right: 20px;
  display: flex;
  flex-direction: column;
}

.right-parts {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.left-tree {
  flex: 1;
  overflow-y: auto;
}

.user-space-info {
  margin-top: 10px;
  padding: 10px;
  background: #f7f7f7;
  border-radius: 4px;
}

.progress-box {
  margin-bottom: 5px;
}

.folder-right-operate {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.file-title {
  display: flex;
  padding: 10px;
  border-bottom: 1px solid #e9edf6;
  font-weight: bold;
}

.file-title .item {
  flex: 1;
  padding: 0 10px;
}

.file-title .name {
  flex: 3;
}

.caret-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  margin-left: 5px;
  vertical-align: middle;
}

.sort-caret {
  display: block;
  width: 0;
  height: 0;
}

.ascending {
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-bottom: 4px solid #ccc;
}

.descending {
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 4px solid #ccc;
  margin-top: 3px; /* 添加适当间隔 */
}

.blue-bottom {
  border-bottom-color: #409eff;
}

.blue-top {
  border-top-color: #409eff;
}

.right-list-container {
  flex: 1;
  overflow-y: auto;
  width: 100%;
  font-size: 14px;
}

.right-list-item {
  border-bottom: 1px solid #e9edf6;
  display: flex;
  padding: 17px 22px 17px 13px;
  align-items: center;
}

.right-list-item:hover {
  background: #e9edf6;
}

.right-list-item .input-select-item {
  margin-right: 10px;
}

.right-list-item .item-inner {
  display: flex;
  align-items: center;
  cursor: pointer;
  flex: 3;
  max-width: 450px;
}

.right-list-item .imgs {
  margin-right: 5px;
}

.right-list-options {
  flex: 1;
  text-align: left;
  padding: 0 10px;
}

.link-color {
  color: #409eff;
  cursor: pointer;
}

.color333 {
  color: #333;
  cursor: pointer;
}

.rec-header {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.recycled-box {
  height: 100%;
}

.title-input {
  margin-right: 10px;
}

.btnPadding815 {
  padding: 8px 15px;
}

.btn-select-bg {
  background: #409eff;
  color: white;
}

/* 确保所有按钮高度一致 */
.btnPadding815 {
  height: 32px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 分页组件样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 15px 0 30px 0;
  border-top: 1px solid #e9edf6;
  margin-top: auto;
  background: #f5f7fa;
}

.pagination-container .el-pagination {
  position: relative;
  z-index: 1001;
}

/* 分页弹出框样式 */
.pagination-popper :deep(.el-select-dropdown__item) {
  padding: 0 20px;
  height: 34px;
  line-height: 34px;
}



/* 设备列表样式 */
.status-online {
  color: #67c23a;
}
.status-offline {
  color: #f56c6c;
}

/* 左侧固定目录样式 */
.fixed-directory {
  margin-top: 10px;
}

.dir-item {
  padding: 8px 1px;
  display: flex;
  align-items: center;
  cursor: pointer;
  border-radius: 4px;
}

.dir-item:hover {
  background-color: #ecf5ff;
}

.dir-item.active {
  background-color: #ecf5ff;
  color: #409eff;
}

.folder-icon {
  margin-right: 5px;
}

.open-folder {
  transform: rotate(0deg);
}

.dir-label {
  flex: 1;
  font-size: 14px;
}

.expand-icon {
  font-size: 10px;
  transition: transform 0.3s;
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

.sub-items {
  margin-left: 20px;
}

.sub-item {
  padding: 6px 10px;
  cursor: pointer;
  font-size: 13px;
  border-radius: 4px;
}

.sub-item:hover {
  background-color: #f5f7fa;
}

/* 面包屑样式优化 */
.bread-box {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
  color: #66b1ff;
  width: 100%;
  overflow: hidden;
}

.bread-box > div {
  margin: 0 !important;
  padding: 0 !important;
}

.bread-box .l {
  cursor: pointer;
  display: flex;
  align-items: center;
  flex-shrink: 0;
  margin: 0 !important;
  padding: 0 !important;
}

.bread-box .nav {
  display: flex;
  margin-left: 0 !important;
  flex-wrap: nowrap;
  flex-shrink: 0;
  margin: 0 !important;
  padding: 0 !important;
}

.bread-box .nav .l {
  display: flex;
  align-items: center;
}

.bread-box .nav .item {
  cursor: pointer;
  margin-right: 0;
  white-space: nowrap;
  flex-shrink: 0;
}

.bread-box .nav .item:last-child {
  color: #333;
}

.bread-box .nav .item:last-child span {
  display: none;
}

.bread-box .nav-item {
  cursor: pointer;
  margin: 0;
  padding: 0;
  white-space: nowrap;
}
</style>